package lecode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 数字字符串格式化 {

    public static void main(String[] args) {
//        System.out.println(solution("1294512.12412").equals("1,294,512.12412"));
//        System.out.println(solution("0000123456789.99").equals("123,456,789.99"));
//        System.out.println(solution("987654321").equals("987,654,321"));
        System.out.println(solution2("1294512.12412").equals("1,294,512.12412"));
        System.out.println(solution2("0000123456789.99").equals("123,456,789.99"));
        System.out.println(solution2("987654321").equals("987,654,321"));
    }


    public static String solution(String s) {
        String[] split = s.split("\\.");
        System.out.println(Arrays.toString(split));
        String pre = split[0];
        char[] charArray = pre.toCharArray();
        //去除前面的0
        int index = 0;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == '0' && i == index) {
                index++;
            }else {
                res.append(charArray[i]);
            }
        }
        System.out.println(res.toString());

        //添加,号
        char[] chars = res.toString().toCharArray();
        StringBuilder tag = new StringBuilder();
        int index1 = 1;
        for (int i = chars.length-1; i >=0 ; i--) {
            if (index1 == 3){
                index1=1;
                tag.append(chars[i]);
                if (i != 0){
                    tag.append(",");
                }
            }else {
                tag.append(chars[i]);
                index1++;
            }
        }
        tag.reverse();
        String results = "";
        if (split.length > 1){
            results = tag.append(".").append(split[1]).toString();
        }else {
            results = tag.toString();
        }
        System.out.println(results);
        return results;
    }


    public static String solution2(String s) {
        // 分割整数部分和小数部分
        String[] split = s.split("\\.");
        String pre = split[0];

        // 去除前面的0
        int index = 0;
        while (index < pre.length() && pre.charAt(index) == '0') {
            index++;
        }
        pre = pre.substring(index);

        // 添加千分位逗号
        StringBuilder tag = new StringBuilder();
        int count = 0;
        for (int i = pre.length() - 1; i >= 0; i--) {
            if (count == 3) {
                tag.append(",");
                count = 0;
            }
            tag.append(pre.charAt(i));
            count++;
        }
        tag.reverse();

        // 拼接小数部分
        if (split.length > 1) {
            tag.append(".").append(split[1]);
        }
        return tag.toString();
    }
}
